package com.sujeet.activity.tracker.model.access;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.sujeet.activity.tracker.model.Activity;

public class CreateSampleData {
	
	private static final String PERSISTENCE_UNIT_NAME = "activity";
	private static EntityManagerFactory factory;
	
	public static void create() {
		factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
		EntityManager em = factory.createEntityManager();
		
		em.getTransaction().begin();
		
		Query q = em.createQuery("select a from Activity a");
		
		boolean notCreated = (q.getResultList().size() == 0);
		
		if(notCreated) {
			for(int i=0; i<5; i++) {
				Activity activity = new Activity();
				Date date = new Date();
				activity.setStartDate(new Date());
				activity.setEstimatedEffort(0.0D);
				activity.setChangeLog(date + ": created");
				em.persist(activity);
			}			
		}
		
		em.getTransaction().commit();	
		
		em.close();
	}
	
	public String getAllActivitiesText() {
		EntityManager em = factory.createEntityManager();
		em.getTransaction().begin();
		StringBuilder returnValue = new StringBuilder();
		Query q = em.createQuery("select a from Activity a");
		@SuppressWarnings("unchecked")
		List<Activity> activityEntries = (List<Activity>) q.getResultList();
		for (Activity anActivity : activityEntries) {
			returnValue.append(anActivity);
			returnValue.append('\n');
		}
		em.close();
		return returnValue.toString();
	}
}
